package com.luoying.itew.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bigkoo.pickerview.TimePickerView;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.Gson;
import com.luoying.itew.R;
import com.luoying.itew.activity.InformationActivity;
import com.luoying.itew.adapter.MyXFormatter;
import com.luoying.itew.bean.AngleRBean;
import com.luoying.itew.bean.DisplacementDirectionBean;
import com.luoying.itew.bean.DisplacementDirectionDayBean;
import com.luoying.itew.bean.DisplacementSpeedBean;
import com.luoying.itew.bean.MoniterRBean;
import com.luoying.itew.common.AntaiApplication;
import com.luoying.itew.http.BaseMap;
import com.luoying.itew.http.HttpRequestUtils;
import com.luoying.itew.http.HttpResponseCallBack;
import com.luoying.itew.manage.LineChartManage;
import com.luoying.itew.util.LogUtils;
import com.luoying.itew.util.ZXWUtils;
import com.luoying.itew.view.ButtonItemView;
import com.luoying.itew.view.ChartsTypeItemView;
import com.luoying.itew.view.LineChartInViewPager;
import com.luoying.itew.view.MyMarkerView;
import com.luoying.itew.view.NewGridView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by lufan on 2019-05-06
 * Class describe 环境图表
 */
public class ChartsWeatherFragment extends BaseFragment implements ChartListener {
    private static final String TAG = "ChartsWeatherFragment";
    @BindView(R.id.gv_charts_one)
    GridView gvChartsOne;
    @BindView(R.id.line_graphic_news)
    LineChartInViewPager lineChart;
    @BindView(R.id.gv_charts_two)
    GridView gvChartsTwo;
    @BindView(R.id.gv_charts_three)
    GridView gvChartsThree;
    @BindView(R.id.gv_charts_type)
    NewGridView gvChartsType;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.rl_start_time)
    RelativeLayout rlStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.rl_end_time)
    RelativeLayout rlEndTime;
    @BindView(R.id.rl_search)
    RelativeLayout rlSearch;
    @BindView(R.id.lr_chart_search)
    LinearLayout lrChartSearch;
    @BindView(R.id.tv_hour_chart)
    TextView tvHourChart;
    @BindView(R.id.tv_chart_fen)
    TextView tvChartFen;
    @BindView(R.id.tv_day_chart)
    TextView tvDayChart;
    @BindView(R.id.rl_chart_others)
    RelativeLayout rlChartOthers;
    @BindView(R.id.sp_type)
    Spinner spType;
    @BindView(R.id.rl_sp_type)
    RelativeLayout rlSpType;
    private String startTime;
    private String endTime;
    private ChartsWeatherFragment.MyAdapter adapterOne;
    private MoniterRBean bean;
    private ChartsWeatherFragment.MyTwoAdapter adapterTwo;
    private ChartsWeatherFragment.MyThreeAdapter adapterThree;
    private int chartBigType = 2;       // 1 位移 2 倾角 3水位
    private int chartMiddelType = 1;   //1 位移走势 2 位移速度 3 位移加速度
    private int chartSmallType = 1;    //1 水平位移/水平速度/水平加速度 2 沉降位移/沉降速度/沉降加速度
    private int axis = 0;   //0 表示x轴  1 表示y轴   （int）
    private int angleType= 3;  //1 倾斜角变化量  2 倾斜率  3 温度  4 湿度  （String） 5 （大气压 app标记用没有和后台定义）
    private int waterType = 1 ;//1 水位时趋势图 (String)
    private ArrayList<Integer> colours;
    private List<String> legendDatas;
    private ChartsWeatherFragment.ChartTypeAdapter chartTypeAdapter;
    private List<String> categoryDatas;
    private int onClick; //0-big 1-middle 2 - small
    private ProgressDialog dialog;
    private DisplacementSpeedBean displacementSpeedBean;
    private int isFirstRefresh;
    private XAxis xAxis;
    private LineChartManage lineChartManage;
    private YAxis leftAxis;
    private int selectPosition = -1;
    private int dayOrHour = 0;  //0 - 时趋势图 1 - 日趋势图
    private TimePickerView startPickView;
    private TimePickerView endPickView;
    private List<String> selectTypeOne = new ArrayList();


    //数组
    private String[] selectType1 = {
            "温度", "湿度", "大气压",""
    };
    private String[] selectType2 = {
            "位移走势", "位移速度", "位移加速度"
    };
    private String[] selectType3 = {
            "水平位移", "沉降位移"
    };
    int select;

    @Override
    protected int getLayoutResId() {
        return R.layout.charts_weather;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LogUtils.e(TAG, "onCreateView: " );
    }

    @Override
    protected void init() {
        super.init();
        initThings();
        //showLoadDialog();
        loadDialog.show();
        initChart();
        setGirdView();
        sendRequest(-1);
        if(getActivity()!=null&&getActivity() instanceof InformationActivity){
            ((InformationActivity)getActivity()).setListenerList(this);
            gvChartsOne.post(new Runnable() {
                @Override
                public void run() {
                    ((InformationActivity)getActivity()).getMoitorDetail();
                }
            });
        }
    }




    private void initChart() {
        lineChartManage = new LineChartManage(lineChart);// no description text
        lineChart.getDescription().setEnabled(false);   //设置描述
        lineChart.setTouchEnabled(true);    //设置是否可以触摸
        lineChart.setDragDecelerationFrictionCoef(0.9f);    //设置滚动时的速度快慢
        lineChart.setDragEnabled(true);     // 是否可以拖拽
        lineChart.setScaleXEnabled(true);
        lineChart.setScaleYEnabled(false);
        //lineChart.setScaleEnabled(true);    // 是否可以缩放 x和y轴, 默认是true
        lineChart.setDrawGridBackground(false);//设置图表内格子背景是否显示，默认是false
        lineChart.setHighlightPerDragEnabled(true);//能否拖拽高亮线(数据点与坐标的提示线)，默认是true
        lineChart.setBackgroundColor(Color.WHITE);  //设置背景颜色
        // 设置MarkerView
        MarkerView mv = new MyMarkerView(getContext(), R.layout.markview_chart);
        lineChart.setMarkerView(mv);
        xAxis = lineChart.getXAxis();

        xAxis.setLabelRotationAngle(25f);  //设置旋转偏移量
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置标签文本格式
        xAxis.setTextSize(10f);
        //设置标签文本颜色
        xAxis.setTextColor(Color.rgb(255, 192, 56));
        //是否绘制轴线
        xAxis.setDrawAxisLine(true);
        //是否绘制网格线
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f);

        leftAxis = lineChart.getAxisLeft();
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setDrawGridLines(true);    //设置左边的网格线显示
        leftAxis.setGranularityEnabled(false);//启用在放大时限制y轴间隔的粒度特性。默认值：false。
        leftAxis.setTextColor(Color.rgb(255, 192, 56)); //设置Y轴文字颜色

        YAxis rightAxis = lineChart.getAxisRight(); //获取右边的Y轴
        rightAxis.setEnabled(false);   //设置右边的Y轴不显示


        //设置图例（也就是曲线的标签）
        Legend legend = lineChart.getLegend();//设置比例图
        //legend.setForm(Legend.LegendForm.NONE);
        //legend.setTextColor(Color.TRANSPARENT);
        legend.setEnabled(false);   //设置不显示比例图
    }

    private void showLoadDialog() {
        if (dialog == null) {
            dialog = new ProgressDialog(getContext());
        }
        dialog.setCanceledOnTouchOutside(false);
        dialog.setMessage("正在加载中");
        dialog.show();
    }

    /**
     * 提前设置颜色集合
     */
    private void initThings() {
        //颜色集合
        colours = new ArrayList<>();
        colours.add(Color.GREEN);
        colours.add(Color.BLUE);
        colours.add(Color.RED);
        colours.add(Color.CYAN);
        colours.add(Color.BLACK);
        colours.add(Color.GRAY);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
        //获取当前时间
        startTime = "";
        endTime = "";//simpleDateFormat.format(date)
        LogUtils.d(TAG, "startTime == " + startTime + ",endTime == " + endTime);
    }

    /**
     * 传position是为了防止点击速度过快，导致请求到的数据和chartMiddelType参数不一致而产生的数据转换异常
     *
     * @param position -1代表默认值，不为-1代表请求返回的数据体发生更改
     */
    private void sendRequest(final int position) {
        BaseMap baseMap = new BaseMap()
                .put("chartBigType", chartBigType)
                .put("chartMiddelType", chartMiddelType)
                .put("chartSmallType",chartSmallType)
                .put("startDate",startTime)
                .put("endDate",endTime)
                .put("axis",axis)
                .put("rainType",1)
                .put("vibrationType",1)
                .put("angleType",angleType)
                .put("waterType",waterType);
        LogUtils.d(TAG,baseMap.toString());
        HttpRequestUtils.getInstance().getCharts(String.valueOf(AntaiApplication.cuurMonitorId ), dayOrHour
                ,baseMap,new HttpResponseCallBack<Map>() {
                    @Override
                    public void onFail(String message) {
                        if (loadDialog != null) {
                            loadDialog.dismiss();
                        }
                        LogUtils.d(TAG, "onFail == " + message);
                    }

                    @Override
                    public void onSuccess(Map bean) {
                        if (loadDialog != null) {
                            loadDialog.dismiss();
                        }
                        String response = new Gson().toJson(bean);
                        LogUtils.d(TAG, "response == " + response);
                        if (chartBigType == 2){   //倾角
                            AngleRBean angleRBean = new Gson().fromJson(response, AngleRBean.class);
                            try {
                                initAngleBean(angleRBean);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }else {     //水位
                            AngleRBean angleRBean = new Gson().fromJson(response, AngleRBean.class);
                            try {
                                initAngleBean(angleRBean);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }


                    }

                    @Override
                    public void onError(String message) {
                        if (loadDialog != null) {
                            loadDialog.dismiss();
                        }
                        LogUtils.d(TAG, "onError == " + message);
                    }
                });
    }

    private void getAtomsData(){
        HttpRequestUtils.getInstance().getAtmosData(AntaiApplication.cuurMonitorId, startTime, new HttpResponseCallBack<Map>() {
                    @Override
                    public void onFail(String message) {
                        loadDialog.dismiss();
                        LogUtils.e("~~~onFail~","~~~~"+message);
                    }

                    @Override
                    public void onSuccess(Map bean) {
                        loadDialog.dismiss();
                        String response = new Gson().toJson(bean);
                        LogUtils.d(TAG, "response == " + response);
                        AngleRBean angleRBean = new Gson().fromJson(response, AngleRBean.class);
                        try {
                            initAngleBean(angleRBean);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(String message) {
                        loadDialog.dismiss();
                        LogUtils.e("~~~onError~","~~~~"+message);
                    }

                }
        );
    }


    /**
     * 设置倾角数据
     *
     * @param bean
     * @throws Exception
     */
    private void initAngleBean(AngleRBean bean) throws Exception {

        //lineChart.setViewPortOffsets(0f, 0f, 0f, 0f);   //设置当前视图的偏移量（实际图表窗口的两侧偏移量）。 设置这个，将阻止图表自动计算它的偏移量。
        Matrix m = new Matrix();
        m.postScale(1.5f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
        lineChart.getViewPortHandler().refresh(m, lineChart, false);//将图表动画显示之前进行缩放

        lineChart.animateX(1000); // 立即执行的动画,x轴
        leftAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if (chartBigType == 2){ //倾角
                    if (angleType == 1){//1 倾斜角变化量  2 倾斜率  3 温度  4 湿度
                        return ZXWUtils.oneToString(value)+"°";
                    }else if (angleType == 2){   //温度保留一位小数
                        return ZXWUtils.ThreeToString(value);
                    }else if(angleType == 3){
                        return ZXWUtils.oneToString(value)+"°";
                    }else if(angleType == 4){
                        return ZXWUtils.oneToString(value)+"%";
                    }else if(angleType == 5){
                        return ZXWUtils.doubleToString(value)+"hPa";
                    }else {
                        return ZXWUtils.oneToString(value)+"%";
                    }
                }else if (chartBigType == 3){   //水位
                    return ZXWUtils.doubleToString(value)+"m";
                }else {

                }return ZXWUtils.doubleToString(value)+"";

            }
        });
        xAxis.setValueFormatter(new IAxisValueFormatter() { //设置筛选器

            private SimpleDateFormat mFormat = new SimpleDateFormat("MM/dd HH:mm");

            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                long millis = TimeUnit.HOURS.toMillis((long)value);
                return mFormat.format(new Date(millis));
            }
        });


        legendDatas = bean.getLegendDatas();
        List<AngleRBean.SeriesBean> series = bean.getSeries();
        int count =0;
        for (int i = 0; i < series.size(); i++) {
            count = count+series.get(i).getData().size();
        }
        boolean noData =legendDatas==null||legendDatas.size()==0||series.size()==0||count==0;
        if (noData){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    lineChart.setNoDataText("暂无数据");
                    lineChart.setNoDataTextColor(Color.BLACK);
//                    mChart.setDescription(null);
                    lineChart.clear();
                    lineChart.invalidate();
//                    mChart.refreshDrawableState();
                }
            },100);
            return;
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        for (int i = 0; i < series.size(); ++i) {
            AngleRBean.SeriesBean seriesBean = series.get(i);
            String collectorName = seriesBean.getName();
            List<AngleRBean.SeriesBean.DataBean> data = seriesBean.getData();
            if (data == null || data.size() == 0) {
                break;
            }
            List<Entry> entries = new ArrayList<>(data.size());
            for (int j = 0; j < data.size(); ++j) {
                AngleRBean.SeriesBean.DataBean dataBean = data.get(j);   //第J条线

                String timestampStr = dataBean.getName();
                List<String> value = dataBean.getValue();
                if (!TextUtils.isEmpty(timestampStr)) {
                    double displacement = Double.valueOf(value.get(1));
                    long timestamp = format.parse(timestampStr).getTime();
                    float hour = TimeUnit.MILLISECONDS.toHours(timestamp);
                    entries.add(new Entry(hour, (float) displacement));
                }

            }
            LineDataSet lineDataSet = new LineDataSet(entries, collectorName);      //将第J条线的坐标点集合和名字传入构造

            lineChartManage.initLineDataSet(lineDataSet, colours.get(i%colours.size()), false);    //将颜色集合设置进去，设置这条线对应的颜色值
            lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);   //设置左右两边Y轴节点描述
            lineDataSet.setValueTextColor(ColorTemplate.getHoloBlue()); //设置节点文字颜色
            lineDataSet.setDrawCircles(false);  //设置是否显示节点的小圆点
            lineDataSet.setDrawValues(false);       //设置是否显示节点的值
            lineDataSet.setHighLightColor(Color.rgb(244, 117, 117));//当点击节点时，将会出现与节点水平和垂直的两条线，可以对其进行定制.此方法为设置线条颜色
            lineDataSet.setHighlightEnabled(true);//设置是否显示十字线
            dataSets.add(lineDataSet);
        }

        LineData data = new LineData(dataSets);     //将线条集合通过构造传入LineData中
        data.setValueTextColor(Color.BLUE);    //设置节点数据值的文本颜色
        data.setValueTextSize(9f);              //设置节点数据值的文字大小
        lineChart.setData(data);            //对象添加lineData数据
        refreshChartType();


    }
    //位移走势中的日趋势图表
    private void setDisplacementDirectionDayData(DisplacementDirectionDayBean displacementDirectionDayBean) {
        try {
            initDisplacementDirectionDayChart(displacementDirectionDayBean);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "无法生成位移图", Toast.LENGTH_LONG).show();
        }
    }

    private void initDisplacementDirectionDayChart(DisplacementDirectionDayBean bean) throws ParseException {
        LogUtils.d(TAG, "日趋势图表开始绘制");
        //lineChart.setViewPortOffsets(0f, 0f, 0f, 0f);   //设置当前视图的偏移量（实际图表窗口的两侧偏移量）。 设置这个，将阻止图表自动计算它的偏移量。
        Matrix m = new Matrix();
        m.postScale(1.5f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
        lineChart.getViewPortHandler().refresh(m, lineChart, false);//将图表动画显示之前进行缩放

        lineChart.animateX(1000); // 立即执行的动画,x轴
        leftAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return ZXWUtils.doubleToString(value) + " mm";
            }
        });
        xAxis.setValueFormatter(new IAxisValueFormatter() { //设置筛选器

            private SimpleDateFormat mFormat = new SimpleDateFormat("MM-dd");

            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                long millis = TimeUnit.DAYS.toMillis((long) value);
                //LogUtils.d(TAG,"X == " + mFormat.format(new Date(millis)));
                return mFormat.format(new Date(millis));
            }
        });


        legendDatas = bean.getLegendDatas();
        List<DisplacementDirectionDayBean.SeriesBean> series = bean.getSeries();
        if (series == null || series.size() == 0) {
            return;
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        for (int i = 0; i < series.size(); ++i) {
            DisplacementDirectionDayBean.SeriesBean seriesBean = series.get(i);
            String collectorName = seriesBean.getName();
            List<DisplacementDirectionDayBean.SeriesBean.DataBean> data = seriesBean.getData();
            if (data == null || data.size() == 0) {
                break;
            }
            List<Entry> entries = new ArrayList<>(data.size());
            for (int j = 0; j < data.size(); ++j) {
                DisplacementDirectionDayBean.SeriesBean.DataBean dataBean = data.get(j);   //第J条线

                String timestampStr = dataBean.getName();
                List<String> value = dataBean.getValue();
                if (!TextUtils.isEmpty(timestampStr)) {
                    double displacement = Double.valueOf(value.get(1));
                    long timestamp = format.parse(timestampStr).getTime();
                    long days = TimeUnit.MILLISECONDS.toDays(timestamp);
                    //float hour = TimeUnit.MILLISECONDS.toHours(timestamp);
                    entries.add(new Entry(days, (float) displacement));     //第J条线的坐标点
                }

            }
            LineDataSet lineDataSet = new LineDataSet(entries, collectorName);      //将第J条线的坐标点集合和名字传入构造

            lineChartManage.initLineDataSet(lineDataSet, colours.get(i%colours.size()), false);    //将颜色集合设置进去，设置这条线对应的颜色值
            lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);   //设置左右两边Y轴节点描述
            lineDataSet.setValueTextColor(ColorTemplate.getHoloBlue()); //设置节点文字颜色
            lineDataSet.setDrawCircles(false);  //设置是否显示节点的小圆点
            lineDataSet.setDrawValues(false);       //设置是否显示节点的值
            lineDataSet.setHighLightColor(Color.rgb(244, 117, 117));//当点击节点时，将会出现与节点水平和垂直的两条线，可以对其进行定制.此方法为设置线条颜色
            lineDataSet.setHighlightEnabled(true);//设置是否显示十字线
            dataSets.add(lineDataSet);
        }

        LineData data = new LineData(dataSets);     //将线条集合通过构造传入LineData中
        data.setValueTextColor(Color.BLUE);    //设置节点数据值的文本颜色
        data.setValueTextSize(9f);              //设置节点数据值的文字大小
        lineChart.setData(data);            //对象添加lineData数据
        refreshChartType();
    }

    //位移走势中的时趋势图表
    private void setDisplacementDirectionData(DisplacementDirectionBean displacementDirectionBean) {
        try {
            initDisplacementDirectionChart(displacementDirectionBean);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "无法生成位移图", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 设置位移速度图表
     *
     * @param displacementSpeedBean
     */
    private void setDisplacementSpeedData(DisplacementSpeedBean displacementSpeedBean) {
        try {
            initDisplacementSpeedChart(displacementSpeedBean);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "无法生成位移图", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 设置位移速度图表的属性
     *
     * @param displacementSpeedBean
     */
    private void initDisplacementSpeedChart(DisplacementSpeedBean displacementSpeedBean) {
        List<DisplacementSpeedBean.SeriesBean> series = displacementSpeedBean.getSeries();
        categoryDatas = displacementSpeedBean.getCategoryDatas();
        legendDatas = displacementSpeedBean.getLegendDatas();
        /*lineChart.getDescription().setEnabled(false);   //设置描述
        lineChart.setTouchEnabled(true);    //设置是否可以触摸
        lineChart.setDragDecelerationFrictionCoef(0.9f);    //设置滚动时的速度快慢
        lineChart.setDragEnabled(true);     // 是否可以拖拽
        lineChart.setScaleXEnabled(true);
        lineChart.setScaleYEnabled(false);
        lineChart.setScaleEnabled(true);    // 是否可以缩放 x和y轴, 默认是true
        lineChart.setDrawGridBackground(false);//设置图表内格子背景是否显示，默认是false
        lineChart.setHighlightPerDragEnabled(true);//能否拖拽高亮线(数据点与坐标的提示线)，默认是true
        lineChart.setBackgroundColor(Color.WHITE);  //设置背景颜色
        LineChartManage lineChartManage = new LineChartManage(lineChart);*/

        Matrix m = new Matrix();
        m.postScale(1.5f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
        lineChart.getViewPortHandler().refresh(m, lineChart, false);//将图表动画显示之前进行缩放

        lineChart.animateX(1000); // 立即执行的动画,x轴
        lineChart.setScaleEnabled(false);

        LogUtils.d(TAG, "SIZE == " + categoryDatas.size());
        MyXFormatter formatter = new MyXFormatter(categoryDatas);
        xAxis.setValueFormatter(formatter);
        leftAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if (chartMiddelType == 2) {//位移速度
                    return ZXWUtils.doubleToString(value) + " mm/周";
                } else {
                    return ZXWUtils.doubleToString(value) + " mm/周²";
                }
            }
        });

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        for (int i = 0; i < series.size(); ++i) {
            DisplacementSpeedBean.SeriesBean seriesBean = series.get(i);
            String collectorName = seriesBean.getName();
            List<DisplacementSpeedBean.SeriesBean.DataBean> data = seriesBean.getData();
            if (data == null || data.size() == 0) {
                break;
            }
            List<Entry> entries = new ArrayList<>(data.size());
            for (int j = 0; j < data.size(); ++j) {

                String aDouble = data.get(j).getValue();
                if (!TextUtils.isEmpty(aDouble)) {
                    entries.add(new Entry(j, Float.valueOf(aDouble)));
                }
            }
            LineDataSet lineDataSet = new LineDataSet(entries, collectorName);      //将第J条线的坐标点集合和名字传入构造

            lineChartManage.initLineDataSet(lineDataSet, colours.get(i%colours.size()), false);    //将颜色集合设置进去，设置这条线对应的颜色值
            lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);   //设置左右两边Y轴节点描述
            lineDataSet.setValueTextColor(ColorTemplate.getHoloBlue()); //设置节点文字颜色
            lineDataSet.setDrawCircles(false);  //设置是否显示节点的小圆点
            lineDataSet.setDrawValues(false);       //设置是否显示节点的值
            lineDataSet.setHighLightColor(Color.rgb(244, 117, 117));//当点击节点时，将会出现与节点水平和垂直的两条线，可以对其进行定制.此方法为设置线条颜色
            lineDataSet.setHighlightEnabled(true);//设置是否显示十字线
            dataSets.add(lineDataSet);
        }
        LineData data = new LineData(dataSets);
        lineChart.setData(data);
        data.setValueTextColor(Color.WHITE);    //设置节点数据值的文本颜色
        data.setValueTextSize(9f);              //设置节点数据值的文字大小
        ++isFirstRefresh;
        if (isFirstRefresh == 1) {   //当数据格式发生改变，此图表就刷新两遍，防止x轴显示不全
            lineChart.setData(data);

        }
        refreshChartType();


    }

    /**
     * 自定义比例图
     */
    private void refreshChartType() {
        chartTypeAdapter = new ChartsWeatherFragment.ChartTypeAdapter(getContext());
        gvChartsType.setAdapter(chartTypeAdapter);
        chartTypeAdapter.notifyDataSetChanged();

    }

    @OnClick({R.id.rl_chart_others, R.id.rl_start_time, R.id.rl_end_time, R.id.rl_search})
    public void onViewClicked(View view) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());// HH:mm:ss
        switch (view.getId()) {
            case R.id.rl_chart_others:  //日趋势图/时趋势图
                loadDialog.show();
                if (dayOrHour == 0) {    //时趋势图
                    //获取当前时间
                    Date date = new Date(System.currentTimeMillis());
                    long currentTimeMills = date.getTime();
                    long startTimeDays = TimeUnit.MILLISECONDS.toDays(currentTimeMills) - 30;
                    long startTimeMillis = TimeUnit.DAYS.toMillis(startTimeDays);
                    startTime =  simpleDateFormat.format(new Date(startTimeMillis));
                    endTime = simpleDateFormat.format(currentTimeMills);
                    dayOrHour = 1;      //时趋势图 -->  日趋势图++
                    tvStartTime.setText("开始时间");
                    tvEndTime.setText("结束时间");
                    rlEndTime.setVisibility(View.VISIBLE);
                    tvDayChart.setTextSize(16);
                    tvDayChart.setTextColor(getResources().getColor(R.color.blue));
                    tvHourChart.setTextSize(14);
                    tvHourChart.setTextColor(getResources().getColor(R.color.gray));
                    sendRequest(-1);
                } else {             //日趋势图
                    dayOrHour = 0;//日趋势图 --> 时趋势图
                    //当前时间
                    startTime = simpleDateFormat.format(new Date());
                    endTime = "";
                    tvStartTime.setText("开始时间");
                    rlEndTime.setVisibility(View.GONE);
                    tvDayChart.setTextSize(14);
                    tvDayChart.setTextColor(getResources().getColor(R.color.gray));
                    tvHourChart.setTextSize(16);
                    tvHourChart.setTextColor(getResources().getColor(R.color.blue));
                    sendRequest(-1);
                    //rlEndTime.setVisibility(View.GONE);
                }
                break;
            case R.id.rl_start_time:    //开始时间
                showStartDateDialog();
                break;
            case R.id.rl_end_time:      //结束时间
                showEndDateDialog();
                break;
            case R.id.rl_search:        //查找
                loadDialog.show();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
                long startTimes = 0;
                long endTimes = 0;
                try {
                    startTimes = format.parse(startTime).getTime();
                    endTimes = format.parse(endTime).getTime();

                } catch (ParseException e) {
                    e.printStackTrace();

                }
                float startDays = TimeUnit.MILLISECONDS.toDays(startTimes);
                float endDays = TimeUnit.MILLISECONDS.toDays(endTimes);
                float values = endDays - startDays;
                LogUtils.d(TAG, "时间差 == " + values);
                if (values > 180) {
                    loadDialog.dismiss();
                    Toast.makeText(getActivity(), "请将时间差控制在半年内", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (values <= 0 && endDays != 0) {
                    loadDialog.dismiss();
                    Toast.makeText(getActivity(), "时间格式错误", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(angleType==5){
                    getAtomsData();
                } else {
                    sendRequest(selectPosition);
                }
                break;
        }
    }

    private void showEndDateDialog() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);
        int mYear = endDate.get(Calendar.YEAR);
        int month = endDate.get(Calendar.DAY_OF_MONTH);
        int date = endDate.get(Calendar.DATE);
        startDate.set(2018, 0, 1);
//        endDate.set(2020,11,31);
        selectedDate.set(mYear, month, date);
        endPickView = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                String tempBirthday = df.format(date);
                LogUtils.d(TAG, "startTime Select == " + tempBirthday + "23:59:59");
                endTime = tempBirthday;
                tvEndTime.setText(tempBirthday);
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTextColorOut(Color.BLACK)
                .setTextColorCenter(0xFF333333)
                .setTitleSize(20)//标题文字大小
                .setTitleText("日期选择")//标题文字
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(0xFF888888)//确定按钮文字颜色
                .setCancelColor(0xFF888888)//取消按钮文字颜色
                .setTitleBgColor(0xFFeeeeee)//标题背景颜色 Night mode
                .setBgColor(0xFFffffff)//滚轮背景颜色 Night mode
                .isCyclic(false)//是否循环滚动
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        endPickView.show();
    }

    private void showStartDateDialog() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);
        //正确设置方式 原因：注意事项有说明
        // mYear = .get(Calendar.YEAR); // 获取当前年份
        int mYear = endDate.get(Calendar.YEAR);
        int month = endDate.get(Calendar.DAY_OF_MONTH);
        int date = endDate.get(Calendar.DATE);
        startDate.set(2018, 0, 1);
//        endDate.set(2020,11,31);
        selectedDate.set(mYear, month, date);
        startPickView = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                String tempBirthday = df.format(date);
                LogUtils.d(TAG, "startTime Select == " + tempBirthday);
                startTime = tempBirthday;
                tvStartTime.setText(tempBirthday);
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTextColorOut(Color.BLACK)
                .setTextColorCenter(0xFF333333)
                .setTitleSize(20)//标题文字大小
                .setTitleText("日期选择")//标题文字
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(0xFF888888)//确定按钮文字颜色
                .setCancelColor(0xFF888888)//取消按钮文字颜色
                .setTitleBgColor(0xFFeeeeee)//标题背景颜色 Night mode
                .setBgColor(0xFFffffff)//滚轮背景颜色 Night mode
                .isCyclic(false)//是否循环滚动
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        startPickView.show();
    }


    @Override
    public void onDataUpdate() {
        if(getActivity()==null)
            return;
        boolean isWater = ((InformationActivity)getActivity()).isWaterCollector();
        selectTypeOne.clear();
        selectTypeOne.add("温度" );
        selectTypeOne.add("湿度" );
        if(isWater){
            selectTypeOne.add("大气压" );
        }
        adapterOne.notifyDataSetChanged();
    }


    class ChartTypeAdapter extends BaseAdapter {
        int mposition;
        //上下文对象
        private Context context;


        ChartTypeAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            if (legendDatas!=null){
                return legendDatas.size();
            }else {
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, final View convertView, ViewGroup parent) {
            mposition = position;

            final ChartsTypeItemView button;
            if (convertView == null) {

                button = new ChartsTypeItemView(context);

            } else {
                button = (ChartsTypeItemView) convertView;
            }

            button.setText(legendDatas.get(position%legendDatas.size()), colours.get(position%colours.size()));//为ImageView设置图片资源
            return button;

        }
    }

    /**
     * 设置位移走势图表的具体属性
     *
     * @param bean
     * @throws Exception
     */
    private void initDisplacementDirectionChart(DisplacementDirectionBean bean) throws Exception {

        //lineChart.setViewPortOffsets(0f, 0f, 0f, 0f);   //设置当前视图的偏移量（实际图表窗口的两侧偏移量）。 设置这个，将阻止图表自动计算它的偏移量。
        Matrix m = new Matrix();
        m.postScale(1.5f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
        lineChart.getViewPortHandler().refresh(m, lineChart, false);//将图表动画显示之前进行缩放

        lineChart.animateX(1000); // 立即执行的动画,x轴
        leftAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return ZXWUtils.doubleToString(value) + " mm";
            }
        });
        xAxis.setValueFormatter(new IAxisValueFormatter() { //设置筛选器

            private SimpleDateFormat mFormat = new SimpleDateFormat("MM/dd HH:mm");

            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                long millis = TimeUnit.HOURS.toMillis((long) value);
                return mFormat.format(new Date(millis));
            }
        });


        legendDatas = bean.getLegendDatas();
        List<DisplacementDirectionBean.SeriesBean> series = bean.getSeries();


        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        for (int i = 0; i < series.size(); ++i) {
            DisplacementDirectionBean.SeriesBean seriesBean = series.get(i);
            String collectorName = seriesBean.getName();
            List<DisplacementDirectionBean.SeriesBean.DataBean> data = seriesBean.getData();
            if (data == null || data.size() == 0) {
                break;
            }
            List<Entry> entries = new ArrayList<>(data.size());
            for (int j = 0; j < data.size(); ++j) {
                DisplacementDirectionBean.SeriesBean.DataBean dataBean = data.get(j);   //第J条线

                String timestampStr = dataBean.getName();
                List<String> value = dataBean.getValue();
                if (!TextUtils.isEmpty(timestampStr)) {
                    double displacement = Double.valueOf(value.get(1));
                    long timestamp = format.parse(timestampStr).getTime();
                    float hour = TimeUnit.MILLISECONDS.toHours(timestamp);
                    entries.add(new Entry(hour, (float) displacement));     //第J条线的坐标点
                }

            }
            LineDataSet lineDataSet = new LineDataSet(entries, collectorName);      //将第J条线的坐标点集合和名字传入构造

            lineChartManage.initLineDataSet(lineDataSet,colours.get(i%colours.size()), false);    //将颜色集合设置进去，设置这条线对应的颜色值
            lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);   //设置左右两边Y轴节点描述
            lineDataSet.setValueTextColor(ColorTemplate.getHoloBlue()); //设置节点文字颜色
            lineDataSet.setDrawCircles(false);  //设置是否显示节点的小圆点
            lineDataSet.setDrawValues(false);       //设置是否显示节点的值
            lineDataSet.setHighLightColor(Color.rgb(244, 117, 117));//当点击节点时，将会出现与节点水平和垂直的两条线，可以对其进行定制.此方法为设置线条颜色
            lineDataSet.setHighlightEnabled(true);//设置是否显示十字线
            dataSets.add(lineDataSet);
        }

        LineData data = new LineData(dataSets);     //将线条集合通过构造传入LineData中
        data.setValueTextColor(Color.BLUE);    //设置节点数据值的文本颜色
        data.setValueTextSize(9f);              //设置节点数据值的文字大小
        lineChart.setData(data);            //对象添加lineData数据
        refreshChartType();


    }

    private void setGirdView() {
        startTime  =   new SimpleDateFormat  ("yyyy-MM-dd",Locale.getDefault()).format(new Date());
        spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                LogUtils.d(TAG, ",XY position == " + position);
                axis = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        adapterOne = new ChartsWeatherFragment.MyAdapter(getContext());
        gvChartsOne.setAdapter(adapterOne);
        gvChartsOne.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //showLoadDialog();
                loadDialog.show();

//                chartBigType = position + 1;
                select = position;  //单选效果
                if(position==0){
                    //温度
                    angleType =3;
                } else if(position==1) {
                    //湿度
                    angleType =4;
                }else if(position==2) {
                    //大气压
                    angleType =5;
                    getAtomsData();
                }
                selectTwo = 0;
                adapterOne.notifyDataSetChanged();
//                adapterTwo.notifyDataSetChanged();
                // TODO
                sendRequest(-1);
                selectPosition = -1;
            }
        });

        adapterTwo = new ChartsWeatherFragment.MyTwoAdapter(getContext());
        gvChartsTwo.setAdapter(adapterTwo);
        gvChartsTwo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //showLoadDialog();
                loadDialog.show();

                chartMiddelType = position + 1;
                selectTwo = position;
                LogUtils.d(TAG, selectType2[position]);
                adapterTwo.notifyDataSetChanged();
                // TODO
                if (chartBigType == 1) { //位移
                    if (position == 0) {    //位移走势
                        selectType3 = new String[]{"水平位移", "沉降位移"};
                        lrChartSearch.setVisibility(View.VISIBLE);
                        rlChartOthers.setVisibility(View.VISIBLE);
                    } else if (position == 1) { //位移速度
                        selectType3 = new String[]{"水平速度", "沉降速度"};
                        lrChartSearch.setVisibility(View.GONE);
                        rlChartOthers.setVisibility(View.GONE);

                    } else if (position == 2) {     //位移加速度
                        selectType3 = new String[]{"水平加速度", "沉降加速度"};
                        lrChartSearch.setVisibility(View.GONE);
                        rlChartOthers.setVisibility(View.GONE);

                    }
                    adapterThree.notifyDataSetChanged();
                } else if (chartBigType == 2) {//倾角
//                    angleType = position+1;
                    if (position == 0) {        //倾斜角变化量
                        LogUtils.d(TAG,"倾角-倾斜角变化量");
                        rlSpType.setVisibility(View.VISIBLE);
                        lrChartSearch.setVisibility(View.VISIBLE);
                        rlChartOthers.setVisibility(View.VISIBLE);
                        tvDayChart.setVisibility(View.VISIBLE);
                    } else if (position == 1) {     //倾斜率
                        LogUtils.d(TAG,"倾角-倾斜率");
                        rlSpType.setVisibility(View.VISIBLE);
                        lrChartSearch.setVisibility(View.VISIBLE);
                        rlChartOthers.setVisibility(View.VISIBLE);
                        tvDayChart.setVisibility(View.VISIBLE);
                    }
                } else if (chartBigType == 3){ //水位时趋势图
                    LogUtils.d(TAG,"水位时趋势图");
                    rlSpType.setVisibility(View.GONE);
                    lrChartSearch.setVisibility(View.GONE);
                    rlChartOthers.setVisibility(View.GONE);
                }

                sendRequest(position + 1);
                selectPosition = position + 1;
            }
        });

        adapterThree = new ChartsWeatherFragment.MyThreeAdapter(getContext());
        gvChartsThree.setAdapter(adapterThree);
        gvChartsThree.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //showLoadDialog();
                loadDialog.show();
                chartSmallType = position + 1;
                selectThree = position;
                LogUtils.d(TAG, selectType3[position]);
                adapterThree.notifyDataSetChanged();
                // TODO
                sendRequest(-1);
                selectPosition = -1;
            }
        });
    }




    class MyAdapter extends BaseAdapter {
        int mposition;
        //上下文对象
        private Context context;


        MyAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return selectTypeOne.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, final View convertView, ViewGroup parent) {
            mposition = position;

            final ButtonItemView button;
            if (convertView == null) {

                button = new ButtonItemView(context);

            } else {
                button = (ButtonItemView) convertView;
            }
            if (select == position) {
                button.setSelect();
            } else {
                button.setNormal();
            }
            button.setText(selectTypeOne.get(position));
            return button;

        }
    }

    private int selectTwo;

    class MyTwoAdapter extends BaseAdapter {
        int mposition;
        //上下文对象
        private Context context;


        MyTwoAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return selectType2.length;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, final View convertView, ViewGroup parent) {
            mposition = position;

            final ButtonItemView button;
            if (convertView == null) {

                button = new ButtonItemView(context);

            } else {
                button = (ButtonItemView) convertView;
            }
            if (selectTwo == position) {
                button.setSelect();
            } else {
                button.setNormal();
            }
            button.setText(selectType2[position]);//为ImageView设置图片资源
            return button;

        }
    }

    private int selectThree;

    class MyThreeAdapter extends BaseAdapter {
        int mposition;
        //上下文对象
        private Context context;


        MyThreeAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return selectType3.length;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, final View convertView, ViewGroup parent) {
            mposition = position;

            final ButtonItemView button;
            if (convertView == null) {

                button = new ButtonItemView(context);

            } else {
                button = (ButtonItemView) convertView;
            }
            if (selectThree == position) {
                button.setSelect();
            } else {
                button.setNormal();
            }
            button.setText(selectType3[position]);//为ImageView设置图片资源
            return button;

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(getActivity()!=null){
            ((InformationActivity)getActivity()).removeListener(this);
        }
    }
}
